from rest_framework import serializers
from .models import Classification, Commodity, CommodityImg, ShoppingCart, Order, Payment
from rest_framework.serializers import SerializerMethodField


# 商品分类序列化器(主要用于一级标题)
class ClassificationSerializer(serializers.ModelSerializer):
    # 选择模型和展示字段
    class Meta:
        model = Classification
        exclude = ['is_delete', 'create_time', 'update_time']


# 商品分类序列化器(用于第一级标题后面的数据)
class ClassificationSerializerSimple(serializers.ModelSerializer):
    classification_set = ClassificationSerializer(many=True, read_only=True)

    # 选择模型和展示字段
    class Meta:
        model = Classification
        exclude = ['is_delete', 'create_time', 'update_time', 'parent']


# 图片序列化器
class CommodityImgSerializer(serializers.ModelSerializer):
    # 指定模型和展示字段
    class Meta:
        model = CommodityImg
        fields = ['src']


# 商品详情序列化器
class CommoditySerializer(serializers.ModelSerializer):
    # 一级分类
    classification1_name = serializers.CharField(source='classification1.name', read_only=True)
    # 二级分类
    classification2_name = serializers.CharField(source='classification2.name', read_only=True)
    # 图片地址
    commodityimg_set = CommodityImgSerializer(many=True, read_only=True)

    # 选择模型和展示字段
    class Meta:
        model = Commodity
        exclude = ['is_delete', 'create_time', 'update_time']

        extra_kwargs = {
            'sales': {'read_only': True},
            'comments': {'read_only': True},
        }


# 购物车序列化器
class ShoppingCartSerializer(serializers.ModelSerializer):
    # 增加一个新字段,用来展示购物车中的商品详情
    commodityDetail = SerializerMethodField()

    # 指定模型和展示字段
    class Meta:
        model = ShoppingCart
        fields = '__all__'

    # 增加校验方法
    def validate(self, attrs):
        # 如果前端传过来的个数小于0
        if attrs['number'] < 0:
            raise serializers.ValidationError('商品数量不能小于0')
        # 如果传过来的个数大于了我的库存个数
        if attrs['number'] > attrs['commodity'].stock:
            raise serializers.ValidationError('商品库存不足')
        return attrs

    # 增加方法,去展示购物车商品详情
    def get_commodityDetail(self, shoppingcart):
        return CommoditySerializer(shoppingcart.commodity).data


# 订单序列化器
class OrderSerializer(serializers.ModelSerializer):
    # 设置模型和展示字段
    class Meta:
        model = Order
        fields = '__all__'
        # 设置只有地址和支付方式用户可写,其他的用户只可以读
        read_only_fields = ['order_id', 'total_count', 'status', 'total_number', 'user']


# 支付订单序列化器
class PaymentSerializer(serializers.ModelSerializer):
    # 模型和展示字段
    class Meta:
        model = Payment
        fields = '__all__'
